<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input placeholder="请输入内容" v-model="search">
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getList(1)"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="12">
          <el-button type="primary" @click="addDialogVisible = true"
            >增加用户</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="dataList" border style="width: 100%">
        <el-table-column prop="id" label="id"></el-table-column>
        <el-table-column prop="username" label="登录名"> </el-table-column>
        <el-table-column prop="is_active" label="激活">
          <template #default="{ row }">
            <el-switch
              v-model="row.is_active"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="switch_change(row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="is_superuser" label="管理员">
          <template #default="{ row }">
            <el-switch
              v-model="row.is_superuser"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="switch_change(row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="phone" label="电话"> </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.id != 1"
              @click="handleClick(scope.row)"
              type="text"
              size="small"
              >编辑</el-button
            >
            <el-button
              type="text"
              size="small"
              v-if="scope.row.id != 1"
              @click="handledelete(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="text"
              size="small"
              v-if="scope.row.id != 1"
              @click="handleresetpassword(scope.row.id)"
              >重置密码</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="pagination.page"
        :page-size="pagination.size"
        layout="total, prev, pager, next, jumper"
        :total="pagination.total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户 -->
    <el-dialog
      title="增加用户"
      :visible.sync="addDialogVisible"
      @close="resetForm('add')"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="add"
        label-
        width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="addForm.checkPass"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 用户详情 -->
    <el-dialog
      title="用户详情"
      :visible.sync="editDialogVisible"
      @close="resetForm('edit')"
    >
      <el-form
        :model="editForm"
        :rules="editRules"
        ref="edit"
        label-
        width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="edit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="重置密码"
      :visible.sync="resetpasswordVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span>这是新密码：{{ newpassword }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="resetpasswordVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  created() {
    this.getList()
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (value !== this.addForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      search: '', // 搜索
      dataList: [],
      pagination: {
        total: 6,
        page: 1,
        size: 2
      },
      // 新增
      addDialogVisible: false,
      resetpasswordVisible: false,
      visible: false,
      newpassword: '',
      addForm: {
        username: '',
        password: '',
        checkPass: '',
        phone: '',
        email: ''
      },
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
        ],
        checkPass: [
          { required: true, message: '请再次输入确认密码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ]
      },
      // 详情
      editDialogVisible: false,
      editForm: {
        username: '',
        phone: '',
        email: ''
      },
      editRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async switch_change(row) {
      console.log(`switch_change : ${row}`)
      const { data: response } = await this.$http.patch(`users/${row.id}/`, {
        is_active: row.is_active,
        is_superuser: row.is_superuser
      })
      if (response.code) {
        return this.$message.error(response.message)
      }
      this.getList(this.pagination.page)
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.getList(val)
    },
    handleClick(row) {
      console.log(`row: ${row}`)
      this.editForm = row
      this.editDialogVisible = true
    },
    handleresetpassword(id) {
      console.log('点击了重置密码', id)
      this.$msgbox
        .confirm('此操作将会重置该用户密码, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(async () => {
          const { data: response } = await this.$http.post(
            `users/${id}/resetpwd/`
          )
          if (response.code) {
            return this.$message.error(response.message)
          }
          this.newpassword = response.newpassword
          this.$message({
            type: 'sucess',
            message: '重置成功'
          })
          this.resetpasswordVisible = true
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handledelete(id) {
      this.$msgbox
        .confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(async () => {
          const { data: response } = await this.$http.delete(`users/${id}/`)
          if (response.code) {
            return this.$message.error(response.message)
          }
          this.getList(1) // 刷新列表
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    resetForm(name) {
      console.log('closing~~~')
      this.$refs[name].resetFields()
    },
    add() {
      const name = 'add'
      this.$refs[name].validate(async (valid) => {
        if (valid) {
          const { data: response } = await this.$http.post(
            'users/',
            this.addForm
          )
          if (response.code) {
            return this.$message.error(response.message)
          }
          this.addDialogVisible = false
          this.getList() // 刷新列表
        }
      })
    },
    async edit() {
      const name = 'edit'
      console.log('edit点击了', this.$refs)
      const { id } = this.editForm
      this.$refs[name].validate(async (valid) => {
        if (valid) {
          const { data: response } = await this.$http.patch(
            `users/${id}/`,
            this.editForm
          )
          if (response.code) {
            return this.$message.error(response.message)
          }
          this.editDialogVisible = false
          this.getList() // 刷新列表
        }
      })
    },
    async getList(page = 1) {
      const { data: response } = await this.$http.get('users/', {
        params: {
          page,
          search: this.search
        }
      })
      if (response.code) {
        return this.$message.error(response.message)
      }
      this.dataList = response.results
      this.pagination = response.pagination
      console.log(this.dataList)
    }
  }
}
</script>
<style lang="less" scoped></style>
